import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import '../../../data/services/channel_service.dart';
import '../../../data/services/search_history_service.dart';

class SearchController extends GetxController {
  // 服务实例
  final ChannelService _channelService = Get.find<ChannelService>();
  final SearchHistoryService _searchHistoryService =
      Get.find<SearchHistoryService>();

  // 搜索输入控制器
  final TextEditingController searchEditingController = TextEditingController();

  // 搜索关键词
  final searchKeyword = ''.obs;

  // 搜索输入框文本
  final searchText = ''.obs;

  // 历史记录列表
  final historyList = <String>[].obs;

  // 搜索结果列表
  final searchResults = <Map<String, dynamic>>[].obs;

  // 是否显示搜索结果
  final showSearchResults = false.obs;

  // 是否正在搜索
  final isSearching = false.obs;

  @override
  void onInit() {
    super.onInit();
    _loadSearchHistory();
    // 监听搜索框文本变化
    searchEditingController.addListener(() {
      searchText.value = searchEditingController.text;
    });
  }

  @override
  void onClose() {
    searchEditingController.dispose();
    super.onClose();
  }

  /// 加载搜索历史记录
  void _loadSearchHistory() {
    try {
      historyList.value = _searchHistoryService.getSearchHistory();
      print('搜索历史加载成功，共${historyList.length}条记录');
    } catch (e) {
      print('加载搜索历史失败: $e');
      historyList.clear();
    }
  }

  /// 搜索
  Future<void> search(String keyword) async {
    if (keyword.trim().isEmpty) return;

    // 添加到历史记录
    await _addToHistory(keyword.trim());

    // 执行搜索
    searchKeyword.value = keyword.trim();
    showSearchResults.value = true;
    isSearching.value = true;

    try {
      // 调用通道列表API进行搜索
      final response = await _channelService.getChannelList(
        queryParam: keyword.trim(),
        pageNo: 1,
        pageSize: 50, // 搜索时加载更多结果
      );

      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        final records = data['records'] as List<dynamic>? ?? [];
        searchResults.value = records.cast<Map<String, dynamic>>();
        print('搜索"$keyword"找到${searchResults.length}个结果');
      } else {
        searchResults.clear();
      }
    } catch (e) {
      print('搜索失败: $e');
      searchResults.clear();
      BotToast.showText(text: '搜索失败，请稍后重试');
    } finally {
      isSearching.value = false;
    }
  }

  /// 添加到历史记录
  Future<void> _addToHistory(String keyword) async {
    try {
      // 保存到本地存储
      await _searchHistoryService.addSearchHistory(keyword);
      // 更新UI显示的历史记录列表
      historyList.value = _searchHistoryService.getSearchHistory();
    } catch (e) {
      print('添加搜索历史失败: $e');
    }
  }

  /// 点击历史记录项
  void onHistoryItemTap(String keyword) {
    searchEditingController.text = keyword;
    search(keyword);
  }

  /// 删除单个历史记录
  Future<void> deleteHistoryItem(String keyword) async {
    try {
      // 从本地存储删除
      await _searchHistoryService.removeSearchHistory(keyword);
      // 更新UI显示的历史记录列表
      historyList.value = _searchHistoryService.getSearchHistory();
    } catch (e) {
      print('删除搜索历史失败: $e');
    }
  }

  /// 清空所有历史记录
  void clearAllHistory() {
    _showClearHistoryDialog();
  }

  /// 显示清空历史记录确认弹框
  void _showClearHistoryDialog() {
    BotToast.showWidget(
      toastBuilder:
          (cancelFunc) => _ClearHistoryDialog(
            onConfirm: () {
              cancelFunc();
              _doClearHistory();
            },
            onCancel: cancelFunc,
          ),
    );
  }

  /// 执行清空历史记录
  Future<void> _doClearHistory() async {
    try {
      // 清空本地存储
      await _searchHistoryService.clearSearchHistory();
      // 更新UI显示的历史记录列表
      historyList.clear();
      BotToast.showText(text: '历史记录已清空');
    } catch (e) {
      print('清空搜索历史失败: $e');
      BotToast.showText(text: '网络环境不佳，请稍后尝试');
    }
  }

  /// 清空搜索结果
  void clearSearchResults() {
    showSearchResults.value = false;
    searchResults.clear();
    searchKeyword.value = '';
    searchText.value = '';
    searchEditingController.clear();
  }

  /// 提交搜索
  void onSearchSubmitted(String value) {
    search(value);
  }

  /// 搜索文本改变
  void onSearchChanged(String value) {
    if (value.isEmpty) {
      clearSearchResults();
    }
  }
}

/// 清空历史记录确认弹框
class _ClearHistoryDialog extends StatelessWidget {
  final VoidCallback onConfirm;
  final VoidCallback onCancel;

  const _ClearHistoryDialog({required this.onConfirm, required this.onCancel});

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Center(
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 60.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.w),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题
              Container(
                padding: EdgeInsets.only(top: 40.w, bottom: 20.w),
                child: Text(
                  '清空历史记录',
                  style: TextStyle(
                    fontSize: 32.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xFF333333),
                  ),
                ),
              ),
              // 内容
              Container(
                padding: EdgeInsets.symmetric(horizontal: 40.w),
                child: Text(
                  '确定要清空所有搜索历史记录吗？',
                  style: TextStyle(
                    fontSize: 28.sp,
                    color: const Color(0xFF666666),
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
              // 分割线
              Container(
                margin: EdgeInsets.only(top: 40.w),
                height: 1.w,
                color: const Color(0xFFF0F0F0),
              ),
              // 按钮
              Row(
                children: [
                  // 取消按钮
                  Expanded(
                    child: GestureDetector(
                      onTap: onCancel,
                      child: Container(
                        height: 88.w,
                        decoration: BoxDecoration(
                          border: Border(
                            right: BorderSide(
                              color: const Color(0xFFF0F0F0),
                              width: 1.w,
                            ),
                          ),
                        ),
                        child: Center(
                          child: Text(
                            '取消',
                            style: TextStyle(
                              fontSize: 32.sp,
                              color: const Color(0xFF666666),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  // 确定按钮
                  Expanded(
                    child: GestureDetector(
                      onTap: onConfirm,
                      child: SizedBox(
                        height: 88.w,
                        child: Center(
                          child: Text(
                            '确定',
                            style: TextStyle(
                              fontSize: 32.sp,
                              color: const Color(0xFF007AFF),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
